//
//  VOLRegisterViewController.m
//  Volver
//
//  Created by administrator on 14-9-19.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLRegisterViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "REFrostedViewController.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"

#import "VOLAppDelegate.h"


@interface VOLRegisterViewController ()
{
    VOLAppDelegate *del;
    JSONDecoder *jd;
    XMPPStream *xmppstream;
    NSString *pwd ;
}
@end

@implementation VOLRegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    del = kGetDel;
    
    self.phoneField.delegate = self;
    self.nameField.delegate = self;
    self.passwordField.delegate = self;
    self.verifyPasswdField.delegate = self;
    
    jd = [[JSONDecoder alloc] init];
    
    self.title = @"用户注册";
    
    addBackButton();
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 返回
-(void)goBack:(id)sender{
    kActionOfMenuButton;
}


#pragma mark 点击空白处收回键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.4 animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

#pragma mark 关闭注册界面
- (IBAction)closeView:(id)sender {
    [UIView animateWithDuration:0.3 animations:^{
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
}
#pragma mark 点击注册
- (IBAction)userRegister:(id)sender {
    NSLog(@"register");
    
    NSString *userPhone = self.phoneField.text;
    NSString *userName = self.nameField.text;
    NSString *userPassword = self.passwordField.text;
    NSString *verifyPassword = self.verifyPasswdField.text;
    
    NSString *alertMessage;
    //判断输入内容是否为空
    if ([userPhone isEqualToString:@""]) {
        alertMessage = @"手机号不能为空！";
        
        if ([userName isEqualToString:@""]) {
            alertMessage = @"姓名不能为空";
            if ([userPassword isEqualToString:@""]) {
                alertMessage = @"手机号、姓名和密码不能为空！";
                if ([verifyPassword isEqualToString:@""]) {
                    alertMessage = @"请输入手机号、姓名和密码！";
                }
            }
        }
        
    }
    else if ([userName isEqualToString:@""]){
        alertMessage = @"姓名不能为空";
    }
    else if ([userPassword isEqualToString:@""]){
        alertMessage = @"密码不能为空！";
    }
    else if ([verifyPassword isEqualToString:@""]){
        alertMessage = @"请输入确认密码";
    }
    else if (![self isValidPhoneNumber:userPhone]){//判断是否为有效手机号
        alertMessage = @"请输入正确的手机号！";
    }
    else if (![self isValidPassword:userPassword]){
        alertMessage = @"请输入6——22位以字母、数字、常用符号（除双引号）组成的密码！";
    }
    else if (![userPassword isEqualToString:verifyPassword]) {
        alertMessage = @"两次输入密码不一致，请重新输入！";
    }
    
    if (alertMessage != nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    __block int isFinishRegister;
    __block MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.labelText = @"正在注册...";
    [HUD showAnimated:YES whileExecutingBlock:^{
        //注册
        isFinishRegister = [self startRegisterUserPhone:userPhone password:userPassword userName:userName];
    } completionBlock:^{
        [HUD removeFromSuperview];
        HUD = nil;
        
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        
        switch (isFinishRegister) {
            case -1://请求失败
            {
                HUD.mode = MBProgressHUDModeText;
                HUD.labelText = @"请求失败";
            }
                break;
            case 0://注册失败
            {
                NSLog(@"注册失败");
                HUD.mode = MBProgressHUDModeText;
                HUD.labelText = @"注册失败";
            }
                break;
            case 1://注册成功
            {
                NSLog(@"注册成功");
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:userPhone forKey:@"userPhone"];
                [userDefaults setObject:userPassword forKey:@"userPassword"];
                
                HUD.mode = MBProgressHUDModeCustomView;
                HUD.labelText = @"注册成功";
                HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Checkmark.png"]];
            }
                break;
                
        }
        //显示
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
            //如果注册成功，返回
            if (isFinishRegister == 1) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }];
        
    }];
    
    
}

#pragma mark 进行注册
-(int)startRegisterUserPhone:(NSString *)userPhone password:(NSString *)userPassword userName:(NSString *)userName{
    
    //获取当前时间
    NSTimeInterval userRegisterTime = kGetCurrentTime;
    
    NSString *urlstr = [NSString stringWithFormat:@"%@user/register",kHTTPHome];
    NSURL *url = [NSURL URLWithString:urlstr];
    
    pwd = [MD5 md5HexDigest:userPassword] ;//获取用户的密码作为全局变量
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:userPhone forKey:@"userPhone"];
    [request setPostValue:[MD5 md5HexDigest:userPassword] forKey:@"userPassword"];
    [request setPostValue:userName forKey:@"userName"];
    [request setPostValue:[NSString stringWithFormat:@"%f",userRegisterTime] forKey:@"userRegisterTime"];
    
    [request setRequestMethod:@"POST"];
    [request startSynchronous];
    
    if (request.error != nil) {
        NSLog(@"请求失败");
        return -1;
    }
    
    
    NSData *data = [request responseData];
    
    NSDictionary *dic = [jd objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    
    //初始化xmppstream
    xmppstream = [[XMPPStream alloc]init];
    [ xmppstream addDelegate:self delegateQueue:dispatch_get_main_queue()];//加入代理
    
    NSError *error = nil ;
    XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@%@",userPhone,kXMPPLocal]];//设置用户名
    [xmppstream setMyJID:jid];
    [xmppstream setHostName:kXMPPID]; //设置服务器名称
    
    //连接服务器
    
    if ([xmppstream connectWithTimeout:5 error:&error]) {
        NSLog(@"xmpp链接服务器成功了");
    }
    
    
    
    
    return status;
    
    
}

#pragma mark 手机号查重
-(int)checkPhoneNumber:(NSString *)phone{
    NSString *urlstr = [NSString stringWithFormat:@"%@user/checkphonenum?userPhone=%@",kHTTPHome,phone];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    if (request.error != nil) {
        NSLog(@"请求失败");
        return -1;
    }
    
    NSData *data = [request responseData];
    if (data == nil) {
        return -2;
    }
    NSDictionary *dic = [jd objectWithData:data];
    return [[dic objectForKey:@"status"] intValue];
    
}




#pragma mark - 验证手机号码是否是有效的
-(BOOL)isValidPhoneNumber:(NSString *)phone{
    
    NSString *phoneRegex = @"^1[3|5|7|8|][0-9]{9}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:phone];
    
}
#pragma mark - 验证密码是否是有效的
-(BOOL)isValidPassword:(NSString *)password{

    NSString *passwordRegex = @"^[a-zA-Z0-9/-:;()$&@,.?!'_#%]{6,12}+$";
    NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passwordRegex];
    return [passwordTest evaluateWithObject:password];
}


#pragma mark - Text Field 代理方法

#pragma mark 自动调整键盘
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    //    CGRect frame = self.passwordField.frame;
    CGRect frame = textField.frame;
    //判断键盘弹出时是否会遮挡输入框，输入框高度30，键盘高度216
    int offset = frame.origin.y + frame.size.height + 15 - (self.view.frame.size.height - 216);
    [UIView animateWithDuration:0.4 animations:^{
        if (offset > 0) {
            CGRect viewFrame = self.view.frame;
            self.view.frame = CGRectMake(0, -offset, viewFrame.size.width, viewFrame.size.height);
        }
    }];
    return YES;
}
#pragma mark 点击return键复原
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.4 animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
    return YES;
}
#pragma mark 手机号查重
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag != 100 || [textField.text isEqualToString:@""]) {
        return;
    }
    
    if (![self isValidPhoneNumber:textField.text]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入有效的手机号！" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    
    int isRepeat = [self checkPhoneNumber:textField.text];
    NSLog(@"%d",isRepeat);
    if (isRepeat) {
        NSLog(@"手机号可用");
    }
    else{
        NSLog(@"手机号已注册过");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"该手机号已注册过，请换一个！" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}


#pragma mark -xmpp链接成功后实现此代理方法
-(void)xmppStreamDidConnect:(XMPPStream *)sender{
    
    NSLog(@"xmp服务器p链接上了");
    
#pragma mark - 向服务器注册账号
    if (![xmppstream registerWithPassword:pwd error:nil]) {
        NSLog(@"注册xmpp账号失败");
    }
    
    
}


#pragma mark - xmpp账号注册成功回调代理函数,再断开连接
-(void)xmppStreamDidRegister:(XMPPStream *)sender{
    
    NSLog(@"xmpp账号注册成功");
    
    //断开该xmpp链接
    [xmppstream disconnect];
    
}
@end






